import django  # 测试单元函数配置
from ruamel import yaml
import os
from dao.project_url import url

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Project.settings')  # 测试单元函数配置
django.setup()  # 测试单元函数配置
from myadmin.models import Cluster

url = url()


def install_cluster(types):
    rs = getName(types)
    if types == 1:  # 1代表spark
        spark(rs[0])
        os.system("kubectl apply -f %s/static/cluster/spark1.yaml" % url)
    elif types == 2:  # 2代表Hadoop
        hadoop(rs[0])
        os.system("kubectl apply -f %s/static/cluster/hadoop1.yaml" % url)
    return rs


def spark(name):
    with open('{}/static/cluster/spark.yaml'.format(url), encoding="utf-8") as f, open(
            '{}/static/cluster/spark1.yaml'.format(url), 'w',
            encoding="utf-8") as nf:
        docs = yaml.load_all(f, Loader=yaml.RoundTripLoader)
        k = 0
        list = []
        for doc in docs:
            if k == 0:
                doc['metadata']['name'] = name
                doc['metadata']['labels']['name'] = name
            else:
                doc['metadata']['namespace'] = name
            # print(doc)
            list.append(doc)
            k += 1
        yaml.dump_all(list, nf, Dumper=yaml.RoundTripDumper)


def hadoop(name):
    with open('{}/static/cluster/hadoop.yaml'.format(url), encoding="utf-8") as f, open(
            '{}/static/cluster/hadoop1.yaml'.format(url), 'w',
            encoding="utf-8") as nf:
        docs = yaml.load_all(f, Loader=yaml.RoundTripLoader)
        k = 0
        list = []
        for doc in docs:
            if k == 0:
                doc['metadata']['name'] = name
            else:
                doc['metadata']['namespace'] = name
            # print(doc)
            list.append(doc)
            k += 1
        yaml.dump_all(list, nf, Dumper=yaml.RoundTripDumper)


def getName(types):
    name_list = ["spark", "hadoop"]
    qs = Cluster.objects.filter(status__exact=0).filter(types__exact=types)
    if qs.exists():
        new_id = qs.first().id
        name = name_list[types - 1] + str(new_id)
        index = new_id
    else:
        new_id = Cluster.objects.last().id + 1
        name = name_list[types - 1] + str(new_id)
        index = 0
    return [name, index]


# if __name__ == '__main__':
#     name = getName(1)
#     print(name)
